package admin

import (
	"github.com/labstack/echo"
	"github.com/sirupsen/logrus"
	"net/http"
	"src/config"
	"src/controller/param"
	"src/model"
	"src/util/context"
	"src/util/log"
	"src/util/token"
)

var adminindexLogger = log.GetLogger()

func writeAdminindexLoggerLoggerLog(funcName, errMsg string, err error) {
	adminindexLogger.WithFields(logrus.Fields{
		"package":  config.LogMessage + "/admin",
		"file":     "index.go",
		"function": funcName,
		"err":      err,
	}).Warn(errMsg)
}

func Login(c echo.Context) error {
	data := param.AdminParam{}
	err := c.Bind(&data)
	if err != nil {
		writeAdminindexLoggerLoggerLog("Login", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorMsgParamWrong)
	}

	ok, err := model.CheckAdminInfo(data.Username, data.Password)
	if !ok {
		writeAdminindexLoggerLoggerLog("Login", "2", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorAdminInfo)
	}
	authData := map[string]interface{}{
		"username": data.Username,
		"admin":    true,
	}
	jwtToken := token.GetJWTToken(authData)

	resData := map[string]interface{}{
		"jwt_token": jwtToken,
	}
	return context.RetData(c, resData)
}

func Creat(c echo.Context) error {
	name := c.QueryParam("name")
	pwd := c.QueryParam("pwd")
	err := model.CreatAdmin(name, pwd)
	if err != nil {
		writeAdminindexLoggerLoggerLog("Creat", "1", err)
		return context.RetError(c, http.StatusBadRequest, http.StatusBadRequest, config.ErrorAdminCreat)
	}
	authData := map[string]interface{}{
		"username": name,
		"admin":    true,
	}
	jwtToken := token.GetJWTToken(authData)

	resData := map[string]interface{}{
		"jwt_token": jwtToken,
	}
	return context.RetData(c, resData)
}
